'use client'

import { useEffect, useState } from 'react'
import { VmsTopic } from '@/types/Model'
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipTrigger, TooltipProvider } from '@/components/ui/tooltip'
import { Input } from '@/components/ui/input'
import Link from 'next/link'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import moment from 'moment'
import { Trash2, Edit, Search, Plus, Filter, Calendar, Target, BarChart3 } from 'lucide-react'
import { toast } from '@/hooks/use-toast'
import { useRouter } from 'next/navigation'

export default function TopicsPage() {
  const [topics, setTopics] = useState<VmsTopic[]>([])
  const [filteredTopics, setFilteredTopics] = useState<VmsTopic[]>([])
  const [loading, setLoading] = useState(true)
  const [showForm, setShowForm] = useState(false)
  const [editTopic, setEditTopic] = useState<VmsTopic | null>(null)
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const router = useRouter()

  const fetchTopics = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/topic', {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        if (response.status === 401) {
          router.push('/login')
          toast({
            title: '登录信息过期',
            description: '请重新登录',
            variant: 'destructive'
          })
          localStorage.clear()
          return
        }
      }
      
      const data = await response.json()
      // Sort by created date descending with null check
      const sortedData = data.sort((a: VmsTopic, b: VmsTopic) => {
        const dateA = a.cjsj ? new Date(a.cjsj).getTime() : 0;
        const dateB = b.cjsj ? new Date(b.cjsj).getTime() : 0;
        return dateB - dateA;
      })
      setTopics(sortedData)
      setFilteredTopics(sortedData)
      toast({
        title: '数据获取成功',
        description: '话题列表已更新',
      })
    } catch (error) {
      console.error('Error fetching topics:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  // 搜索和过滤逻辑
  useEffect(() => {
    let filtered = topics

    // 按搜索词过滤
    if (searchTerm) {
      filtered = filtered.filter(topic => 
        topic.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
        topic.target?.toLowerCase().includes(searchTerm.toLowerCase())
      )
    }

    // 按状态过滤
    if (statusFilter !== 'all') {
      filtered = filtered.filter(topic => topic.status === statusFilter)
    }

    setFilteredTopics(filtered)
  }, [topics, searchTerm, statusFilter])

  useEffect(() => {
    fetchTopics()
  }, [])

  const handleDelete = async (id: string) => {
    try {
      const token = localStorage.getItem('token')
      if (!id) {
        throw new Error('Topic ID is required for deletion')
      }
      const response = await fetch(`/api/topic/${id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('Failed to delete topic')
      }
      
      // Optimistic update instead of refetching
      setTopics(prev => prev.filter(topic => topic.id !== id))
      toast({
        title: '删除成功',
        description: '话题已删除',
      })
    } catch (error) {
      console.error('Error deleting topic:', error)
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      // Revert if error occurs
      fetchTopics()
    }
  }

  const handleEdit = (topic: VmsTopic) => {
    setEditTopic(topic)
    setShowForm(true)
  }

  const handleSubmit = async (topic: VmsTopic) => {
    try {
      const token = localStorage.getItem('token')
      const method = topic.id ? 'PUT' : 'POST'
      const url = topic.id ? `/api/topic` : '/api/topic'
 
    // 双重检查确保 status 不为空
    if (!topic.status || topic.status.trim() === '') {
      topic.status = 'To Do'
    }
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(topic)
      })
      
      if (!response.ok) {
        throw new Error(`Failed to ${topic.id ? 'update' : 'create'} topic`)
      }
      
      const updatedTopic = await response.json()
      
      // Optimistic update
      if (topic.id) {
        setTopics(prev => 
          prev.map(t => t.id === topic.id ? updatedTopic : t)
        )
        toast({
          title: '更新成功',
          description: '话题已更新',
        })
      } else {
        setTopics(prev => [updatedTopic, ...prev])
        toast({
          title: '创建成功',
          description: '新话题已创建',
        })
      }
      
      setShowForm(false)
      setEditTopic(null)
    } catch (error) {
      console.error('Error submitting topic:', error)
      toast({
        title: '操作失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      // Revert if error occurs
      fetchTopics()
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'To Do':
        return 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-700 hover:bg-slate-200 dark:hover:bg-slate-700'
      case 'In Progress':
        return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/30 dark:text-rose-300 dark:border-rose-800 hover:bg-rose-100 dark:hover:bg-rose-900/50'
      case 'Done':
        return 'bg-green-50 text-green-700 border-green-200 dark:bg-green-900/30 dark:text-green-300 dark:border-green-800 hover:bg-green-100 dark:hover:bg-green-900/50'
      default:
        return 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-700 hover:bg-slate-200 dark:hover:bg-slate-700'
    }
  }

  const getProgressColor = (progress: number) => {
    if (progress >= 80) return 'bg-green-500'
    if (progress >= 50) return 'bg-rose-500'
    return 'bg-slate-400'
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white dark:from-slate-900 dark:to-slate-950 flex justify-center items-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-rose-600"></div>
      </div>
    )
  }

  return (
    <TooltipProvider>
      <div className="min-h-screen bg-gradient-to-b from-slate-50 to-white dark:from-slate-900 dark:to-slate-950">
        <div className="container mx-auto py-8 px-4">
          {/* 页面头部 */}
          <div className="mb-8">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-6">
              <div>
                <h1 className="text-3xl font-bold bg-gradient-to-r from-slate-900 to-slate-700 dark:from-white dark:to-slate-300 bg-clip-text text-transparent mb-2">项目管理</h1>
                <p className="text-slate-600 dark:text-slate-400">管理您的所有项目和话题</p>
              </div>
              <Button 
                onClick={() => setShowForm(true)}
                className="bg-gradient-to-r from-rose-600 to-rose-700 hover:from-rose-700 hover:to-rose-800 text-white shadow-lg hover:shadow-xl transition-all duration-200 border-0"
                size="lg"
              >
                <Plus className="h-5 w-5 mr-2" />
                新建项目
              </Button>
            </div>

            {/* 搜索和过滤区域 */}
            <Card className="border-slate-200/50 dark:border-slate-800/50 shadow-sm bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm">
              <CardContent className="p-6">
                <div className="flex flex-col sm:flex-row gap-4">
                  <div className="relative flex-1">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400 h-5 w-5" />
                    <Input
                      placeholder="搜索项目名称或目标..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="pl-10 h-12 border-slate-200 dark:border-slate-700 focus:border-rose-500 focus:ring-rose-500 bg-white dark:bg-slate-800"
                    />
                  </div>
                  <div className="flex items-center gap-2">
                    <Filter className="h-5 w-5 text-slate-400" />
                    <Select value={statusFilter} onValueChange={setStatusFilter}>
                      <SelectTrigger className="w-40 h-12 border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800">
                        <SelectValue placeholder="状态筛选" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="all">全部状态</SelectItem>
                        <SelectItem value="To Do">待开始</SelectItem>
                        <SelectItem value="In Progress">进行中</SelectItem>
                        <SelectItem value="Done">已完成</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                
                {/* 统计信息 */}
                <div className="mt-4 pt-4 border-t border-slate-100 dark:border-slate-800">
                  <div className="flex flex-wrap gap-6 text-sm text-slate-600 dark:text-slate-400">
                    <div className="flex items-center gap-2">
                      <BarChart3 className="h-4 w-4" />
                      <span>总项目: <span className="font-semibold text-slate-900 dark:text-white">{topics.length}</span></span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span>显示: <span className="font-semibold text-slate-900 dark:text-white">{filteredTopics.length}</span></span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span>进行中: <span className="font-semibold text-rose-600">{topics.filter(t => t.status === 'In Progress').length}</span></span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span>已完成: <span className="font-semibold text-green-600">{topics.filter(t => t.status === 'Done').length}</span></span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 项目卡片网格 */}
          {filteredTopics.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-slate-400 text-lg mb-2">暂无项目</div>
              <p className="text-slate-500">创建您的第一个项目开始管理工作流程</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {filteredTopics.map((topic) => {
                const createdDate = topic.cjsj ? moment(topic.cjsj).format('MM-DD') : 'N/A'
                const copyProgress = ((topic.copy_finished_num || 0) / (topic.copy_num || 1)) * 100
                
                return (
                 
                  <Card key={topic.id} className="group hover:shadow-xl transition-all duration-300 border-slate-400/50 dark:border-slate-800/50 shadow-sm hover:-translate-y-1 bg-white/80 dark:bg-slate-900/80 backdrop-blur-sm">
                    <CardHeader className="pb-3">
                      <div className="flex justify-between items-start mb-2">
                        <Badge className={`${getStatusColor(topic.status || 'To Do')} text-xs font-medium border`}>
                          {topic.status}
                        </Badge>
                        <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-8 w-8 hover:bg-rose-50 dark:hover:bg-rose-900/30 hover:text-rose-600 dark:hover:text-rose-400"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleEdit(topic);
                                }}
                              >
                                <Edit className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>编辑项目</TooltipContent>
                          </Tooltip>
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <Button 
                                variant="ghost" 
                                size="icon"
                                className="h-8 w-8 hover:bg-red-50 dark:hover:bg-red-900/30 hover:text-red-600 dark:hover:text-red-400"
                                onClick={async () => {
                                  const confirmWarning = window.confirm(
                                    `警告：这将永久删除项目 "${topic.name}" 及其所有文案和脚本！\n` +
                                    '此操作不可撤销，确定要继续吗？'
                                  )
                                  
                                  if (!confirmWarning) {
                                    toast({
                                      title: '删除取消',
                                      description: '用户取消删除操作',
                                      variant: 'destructive'
                                    })
                                    return
                                  }

                                  const projectName = window.prompt(`请输入项目名称 "${topic.name}" 以确认删除`)
                                  if (projectName !== topic.name) {
                                    toast({
                                      title: '删除取消',
                                      description: '项目名称不匹配',
                                      variant: 'destructive'
                                    })
                                    return
                                  }

                                  if (topic.id) {
                                    await handleDelete(topic.id)
                                  } else {
                                    console.error('Cannot delete topic without ID')
                                  }
                                }}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </TooltipTrigger>
                            <TooltipContent>删除项目</TooltipContent>
                          </Tooltip>
                        </div>
                      </div>
                      <CardTitle className="text-lg leading-tight">
                         <Link href={`/notion?topicid=${topic.id}`} className="block">

                        <Button 
                          variant="link" 
                          className="p-0 text-left font-semibold text-lg h-auto text-slate-900 dark:text-white hover:text-rose-600 dark:hover:text-rose-400 transition-colors"
                        >
                          {topic.name || 'N/A'}
                        </Button>
                        </Link>
                      </CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4 text-sm">
                      <div className="space-y-3">
                        <div className="flex items-start gap-2">
                          <Target className="h-4 w-4 text-slate-400 mt-0.5 flex-shrink-0" />
                          <div>
                            <span className="font-medium text-slate-700 dark:text-slate-300">目标:</span>
                            <p className="text-slate-600 dark:text-slate-400 mt-1 leading-relaxed">
                              {topic.target ? 
                                topic.target.length > 60 ? 
                                  `${topic.target.substring(0, 60)}...` : 
                                  topic.target : 
                                'N/A'}
                            </p>
                          </div>
                        </div>
                        
                        <div className="flex items-center gap-2">
                          <Calendar className="h-4 w-4 text-slate-400" />
                          <span className="font-medium text-slate-700 dark:text-slate-300">创建:</span>
                          <span className="text-slate-600 dark:text-slate-400">{createdDate}</span>
                        </div>
                        
                        <Link href={`/progress?topicid=${topic.id}`} className="block">
                          <div className=" dark:bg-slate-800/50 rounded-lg p-3  transition-colors">
                            <div className="flex items-center justify-between mb-2">
                              <span className="font-medium text-slate-700 dark:text-slate-300">进度</span>
                              <span className="text-sm text-slate-600 dark:text-slate-400">
                                {topic.copy_finished_num || 0}/{topic.copy_num || 0}
                              </span>
                            </div>
                            <div className="relative">
                              <Progress 
                                value={copyProgress} 
                                className="h-2 bg-slate-200 dark:bg-slate-700"
                              />
                              <div 
                                className={`absolute top-0 left-0 h-2 rounded-full transition-all duration-300 ${getProgressColor(copyProgress)}`}
                                style={{ width: `${copyProgress}%` }}
                              />
                            </div>
                            <div className="text-xs text-slate-500 dark:text-slate-400 mt-1">
                              {copyProgress.toFixed(0)}% 完成
                            </div>
                          </div>
                        </Link>
                      </div>
                    </CardContent>
                  </Card>
                  
                )
              })}
            </div>
          )}

          {/* 表单对话框 */}
          <Dialog open={showForm} onOpenChange={(open: boolean) => {
            if (!open) {
              setShowForm(false)
              setEditTopic(null)
            }
          }}>
            <DialogContent className="sm:max-w-[500px] bg-white dark:bg-slate-900 border-slate-200 dark:border-slate-800">
              <DialogHeader>
                <DialogTitle className="text-xl font-semibold text-slate-900 dark:text-white">
                  {editTopic ? '编辑项目' : '新建项目'}
                </DialogTitle>
              </DialogHeader>
              <TopicForm 
                onCancel={() => {
                  setShowForm(false)
                  setEditTopic(null)
                }}
                onSubmit={handleSubmit}
                topic={editTopic}
              />
            </DialogContent>
          </Dialog>
        </div>
      </div>
    </TooltipProvider>
  )
}

interface TopicFormProps {
  topic?: VmsTopic | null
  onCancel: () => void
  onSubmit: (topic: VmsTopic) => void
}

const TopicForm = ({ topic, onCancel, onSubmit }: TopicFormProps) => {
  const [formData, setFormData] = useState<VmsTopic>({
    id: topic?.id || '',
    name: topic?.name || '',
    target: topic?.target || '',
    status: topic?.status || 'To Do',
    cjsj: topic?.cjsj ? moment(topic.cjsj).toDate() : new Date(),
    user_id: topic?.user_id
  })

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? Number(value) : value
    }))
  }

  const handleStatusChange = (value: string) => {
    setFormData(prev => ({
      ...prev,
      status: value
    }))
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit(formData)
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="space-y-4">
        <div>
          <label htmlFor="name" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            项目名称 *
          </label>
          <Input
            id="name"
            name="name"
            type="text"
            value={formData.name}
            onChange={handleChange}
            className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800"
            placeholder="输入项目名称"
            required
          />
        </div>
        
        <div>
          <label htmlFor="target" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            项目目标 *
          </label>
          <textarea
            id="target"
            name="target"
            value={formData.target}
            onChange={handleChange}
            className="w-full min-h-[100px] px-3 py-2 border border-slate-200 dark:border-slate-700 rounded-md focus:outline-none focus:ring-2 focus:ring-rose-500 focus:border-rose-500 bg-white dark:bg-slate-800 text-slate-900 dark:text-white"
            placeholder="描述项目的具体目标和要求"
            required
          />
        </div>
        
        <div>
          <label htmlFor="status" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
            项目状态
          </label>
          <Select value={formData.status} onValueChange={handleStatusChange}>
            <SelectTrigger className="w-full border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800">
              <SelectValue placeholder="选择状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="To Do">待开始</SelectItem>
              <SelectItem value="In Progress">进行中</SelectItem>
              <SelectItem value="Done">已完成</SelectItem>
            </SelectContent>
          </Select>
        </div>
    
      </div>
      
      <div className="flex justify-end gap-3 pt-4 border-t border-slate-200 dark:border-slate-800">
        <Button 
          type="button" 
          variant="outline" 
          onClick={onCancel}
          className="border-slate-200 dark:border-slate-700 text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800"
        >
          取消
        </Button>
        <Button 
          type="submit"
          className="bg-gradient-to-r from-rose-600 to-rose-700 hover:from-rose-700 hover:to-rose-800 text-white border-0"
        >
          {topic ? '更新' : '创建'}
        </Button>
      </div>
    </form>
  )
}
